package com.example.papercut.service.impl;

import com.example.papercut.entity.TemplateRating;
import com.example.papercut.mapper.TemplateRatingMapper;
import com.example.papercut.service.TemplateRatingService;
import org.springframework.stereotype.Service;
import org.springframework.beans.factory.annotation.Autowired;
import java.util.List;

@Service
public class TemplateRatingServiceImpl implements TemplateRatingService {

    private final TemplateRatingMapper ratingMapper;

    @Autowired
    public TemplateRatingServiceImpl(TemplateRatingMapper ratingMapper) {
        this.ratingMapper = ratingMapper;
    }

    /**
     * 提交或更新评分和评论 (直接调用 Mapper 中带 ON DUPLICATE KEY UPDATE 的方法)
     */
    @Override
    public void submitOrUpdateRating(TemplateRating rating) {
        // 业务逻辑校验：确保评分在 1-5 之间
        if (rating.getRatingValue() == null || rating.getRatingValue() < 1 || rating.getRatingValue() > 5) {
            throw new IllegalArgumentException("评分数值必须在 1 到 5 之间");
        }
        
        // 调用 Mapper (MyBatis XML 中已使用 ON DUPLICATE KEY UPDATE 实现插入或更新)
        ratingMapper.insertRating(rating);
    }

    /**
     * 获取指定模板的所有评论
     */
    @Override
    public List<TemplateRating> getRatingsByPapercutId(Integer papercutId) {
        return ratingMapper.findRatingsByPapercutId(papercutId);
    }

    /**
     * 计算指定模板的平均评分
     */
    @Override
    public Double getAverageRating(Integer papercutId) {
        Double avg = ratingMapper.calculateAverageRating(papercutId);
        // 返回 0.0 而非 null，保证 API 友好性
        return avg != null ? avg : 0.0; 
    }

    // ✅ 新增方法实现
    @Override
    public List<TemplateRating> getRatingsByUserId(Integer userId) {
        // 假设 TemplateRatingMapper 中有一个方法可以直接根据 userId 查询
        return ratingMapper.findRatingsByUserId(userId); 
    }
}